package com.cashmama.market.api.domain.picture;

import com.cashmama.market.api.domain.enums.PictureRestErrorEnum;
import com.cashmama.market.api.domain.service.ApiUserQuotaService;
import com.cashmama.market.api.infras.config.ApolloConfigUtil;
import com.fqgj.base.services.amazon.AmazonS3Service;
import com.fqgj.base.services.oss.OSSService;
import com.fqgj.exception.common.ApplicationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @program: market-api
 * @description
 * @author: frank
 * @create: 2020-09-28 17:25
 **/
@Service
public class PictureService {

    private final static Logger LOGGER = LoggerFactory.getLogger(ApiUserQuotaService.class);

    @Autowired
    private ApolloConfigUtil apolloConfigUtil;
    @Autowired
    private AmazonS3Service amazonS3Service;
    @Autowired
    private OSSService ossService;

    public String uploadPicture(HttpServletRequest request, String userCode) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("picture");
        LOGGER.info("=== 开始上传图片2211 userCode:{},size:{}===", userCode, multipartFile.getSize());

        if (multipartFile == null || multipartFile.isEmpty()) {
            throw new ApplicationException(PictureRestErrorEnum.PICTURE_NULL);
        }

        if (multipartFile.getSize() > 10000000) {
            throw new ApplicationException(PictureRestErrorEnum.PICTURE_OVER_SIZE);
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = apolloConfigUtil.isServerTest() ? "jy/test/" + userCode + "/" + uuid : "jy/" + userCode + "/" + uuid + "_B";
        ByteArrayOutputStream outputStream = null;
        InputStream in1 = null;
//        InputStream in2 = null;
        try {
            InputStream inputStream = multipartFile.getInputStream();
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) > -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
            in1 = new ByteArrayInputStream(outputStream.toByteArray());
//            in2 = new ByteArrayInputStream(outputStream.toByteArray());
            ossService.uploadFile(apolloConfigUtil.getBucketName(), in1, multipartFile.getSize(), fileName, "image/jpeg");
//            amazonS3Service.uploadFile(in2, fileName, "image/jpeg");
            LOGGER.info("上传图片成功:{},url:{}", fileName, apolloConfigUtil.getOssBaseUrl() + fileName);
        } catch (Exception e) {
            LOGGER.error("上传图片失败，userCode:" + userCode + ",exception:" + e);
            throw new ApplicationException(PictureRestErrorEnum.PICTURE_UPLOAD);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (in1 != null) {
                    in1.close();
                }
//                if (in2 != null) {
//                    in2.close();
//                }
            } catch (IOException var15) {
            }
        }
        return apolloConfigUtil.getOssBaseUrl() + fileName;
    }
}
